package com.haizhi.exit;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import sun.misc.Signal;
import sun.misc.SignalHandler;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: youfeng
 * Date: 2018-06-25
 * Time: 17:56
 */
public class KillHandler implements SignalHandler {

    private static final Logger logger = LogManager.getLogger(KillHandler.class);

    private StopEnable stopEnable;

    public KillHandler(StopEnable stopEnable) {
        this.stopEnable = stopEnable;
        this.registerSignal();
    }

    private void registerSignal() {
        Signal signal = new Signal("TERM");
        Signal.handle(signal, this);
        signal = new Signal("INT");
        Signal.handle(signal, this);
        signal = new Signal("HUP");
        Signal.handle(signal, this);
    }

    @Override
    public void handle(Signal signal) {

        if (signal.getName().equals("TERM")) {
            stopEnable.shutdown();
            logger.info("收到 {} 信号，退出线程..", signal.getName());
        } else if (signal.getName().equals("INT") || signal.getName().equals("HUP")) {
            stopEnable.shutdown();
            logger.info("收到 {} 信号，退出线程..", signal.getName());
        }
    }

}
